/**
 * indexDB 本地数据库操作
 * @param {object} dbName 数据库的名字
 * @param {string} storeName 仓库名称
 * @param {string} version  数据库的版本
 * @return {object} 该函数会返回一个数据库实例
 */

function openIndexDB(dbName, storeName, version) {
    const promist = new Promise((resolve, reject) => {
        let db, request
        request = window.indexedDB.open(dbName, version)
        request.onsuccess = function (event) {
            db = event.target.result
            resolve(db)
        }
        request.onerror = function (event) {
            reject(event)
            console.log('打开数据库报错---->',);
        }
        request.onupgradeneeded = function (event) {
            console.log('数据库创建或者升级的时候触发---->',);
            db = event.target.result
            let objectStore
            if (!db.objectStoreNames.contains(storeName)) {
                objectStore = db.createObjectStore(storeName, { keyPath: 'id' })
            }
            resolve(db)
        }
    })
    return promist

}

function indexDBAddData(db, storeName, data) {
    const promise = new Promise((resolve, reject) => {

        let request = db.transaction([storeName], 'readwrite').objectStore(storeName).add(data)

        request.onsuccess = function (event) {
            console.log('添加数据库成功---->',);
            resolve(event)
        }
        request.onerror = function (event) {
            console.log('添加数据库报错---->', event);
            reject(event)
        }
    })
    return promise

}

function getDataByKey(db, storeName, key) {
    const promise = new Promise((resolve, reject) => {
        let transaction = db.transaction([storeName])
        let objectStore = transaction.objectStore(storeName)
        let request = objectStore.get(key)

        request.onerror = function (event) {
            console.log('事务失败')
            reject(event)
        }

        request.onsuccess = function (event) {
            console.log('主键查询结果: ', request.result)
            resolve(request.result)
        }
    })
    return promise
}

function updateDB(db, storeName, data) {
    const promise = new Promise((resolve, reject) => {
        let request = db.transaction([storeName], 'readwrite').objectStore(storeName).put(data)
        request.onsuccess = function (event) {
            console.log('数据更新成功')
            resolve(event)
        }

        request.onerror = function (event) {
            console.log('数据更新失败')
            reject(event)
        }
    })
    return promise
}

function deleteDB(db, storeName, id) {
    const promise = new Promise((resolve, reject) => {
        let request = db.transaction([storeName], 'readwrite').objectStore(storeName).delete(id)
        request.onsuccess = function (event) {
            console.log('数据删除成功')
            resolve(event)
        }

        request.onerror = function (event) {
            console.log('数据删除失败')
            reject(event)
        }
    })
    return promise
}

// 从 IndexedDB 中获取数据的函数
async function getAllFromIndexedDB(db, storeName) {
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([storeName], 'readonly');
      const store = transaction.objectStore(storeName);
   
     const request =  store.getAll()
     request.onerror = (event) => {
        reject(event.target.error);
      };
 
      request.onsuccess = (event) => {
        resolve(event.target.result); // 解析为查询结果
        // db.close(); // 关闭数据库连接（可选，但推荐在不再需要数据库时关闭）
      };
      transaction.onerror = (event) => {
        reject(event.target.error);
      };
    });
  }
   

export { indexDBAddData, openIndexDB, updateDB, getDataByKey, deleteDB,getAllFromIndexedDB }